package com.example.timeassistant.network

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object RetrofitClient {
    // 使用 Android 模拟器访问本机后端: 10.0.2.2
//     private const val BASE_URL = "http://work.time1024.cn/api/"
   private const val BASE_URL = "http://10.0.2.2:8080/"

    private val logging = HttpLoggingInterceptor().apply {
        level = HttpLoggingInterceptor.Level.BODY
    }

    private val tokenInterceptor = okhttp3.Interceptor { chain ->
        val original = chain.request()
        val builder = original.newBuilder()
        val token = TokenManager.token
        if (!token.isNullOrBlank()) {
            // 后端不需要 Bearer 前缀，直接传递原始 token
            builder.header("Authorization", token)
        }
        chain.proceed(builder.build())
    }

    private val httpClient: OkHttpClient = OkHttpClient.Builder()
        .addInterceptor(tokenInterceptor)
        .addInterceptor(logging)
        .build()

    val api: ApiService by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(httpClient)
            .build()
            .create(ApiService::class.java)
    }
}